/**
 * 
 */
package com.jm.web.form.baseitem;

import java.sql.ResultSet;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jm.utils.StringHelper;
import com.jm.web.data.BaseDataEntity;
import com.jm.web.data.form.Item;
import com.jm.web.data.form.ListItemCollection;
import com.jm.web.tags.support.BaseTag;

/**
 * @author yanjie
 * 数据集控件
 * 2011/10/6 上午9:31:08
 */
public class ListItem extends BaseItem{
	private final static Log log = LogFactory.getLog(ListItem.class);
	protected ListItemCollection listItemCollection = new ListItemCollection();
	protected String strCodeList = "";//自定义
	

	protected String strSql = "";//sql 
	protected String strDataSource = "";//数据源 eq:info info5
	protected String strCodelistPostion = "BEFORE" ;
	
	protected boolean bEmptysupported = true;//是否支持空值
	protected boolean bAutoEmpty = false;//是否支持空值
	
	protected String strEmptytext = "--";//空值文本
	protected boolean bEmptyatfirst = true;//空值置顶
	protected boolean bload = false;
	protected Map editorMap = null;//表格编辑器对应的数据
	protected Map<String ,BaseDataEntity> recordMap = null;
	boolean brecordMap = false;
	
	
	public ListItemCollection getListItems(){
		return listItemCollection ;
	}
	
	public ListItem() {};
	
	@Override
	public void init() {
		super.init();
		if(!bload)
			loadCodeListItem();
	}
		
	/**
	 * 加載数据集
	 */
	protected void loadCodeListItem(){
		brecordMap = this.getBaseTag().GetExtValue("withRecord", false) && this.getBaseTag().getPage().getListItemRecordMap(this.getName()) == null;
		
		 bload = true;
		if("BEFORE".equalsIgnoreCase(strCodelistPostion)){
			processRawcodelist();
		}
		
		processDataSourcelist();
		
		if("AFTER".equalsIgnoreCase(strCodelistPostion)){
			processRawcodelist();
		}
		
		if(bAutoEmpty && this.listItemCollection.size() == 0){
			this.bEmptysupported = true;
		}if(bAutoEmpty && this.listItemCollection.size() > 0){
			this.bEmptysupported = false;
		}
		
		// 填充其它项目
		if (this.bEmptysupported)
		{
			Item item = new Item("",this.strEmptytext);
			if (this.bEmptyatfirst)
			{
				addListItem(0, item);
			}
			else
			{
				addListItem(item);
			}
		}
		
		if(brecordMap){
			this.getBaseTag().getPage().addListItemRecordMap(this.getName(),recordMap);
		}
	}
	
	protected void addAll(Collection item){
		this.listItemCollection.addAll(item);
	}
	
	protected void addListItem(Item item){
		this.listItemCollection.Add(item);
	}
	
	protected void addListItem(int index,Item item){
		this.listItemCollection.Insert(index, item);
	}
	
	
	/**
	 * 处理动态数据集
	 */
	protected void processDataSourcelist(){
		if(this.getUtils() != null && StringHelper.Length(this.strDataSource) > 0 && StringHelper.Length(this.strSql) > 0){
			try {
				if(this.getBaseTag().isColumnEditor()){
					editorMap = new HashMap();
				}
				
				if(brecordMap){
					if(recordMap == null)
						recordMap = new HashMap<String, BaseDataEntity>();
				}
				
				Vector<Item> temp = null;
				String key = StringHelper.Format("%1$s-%2$s",this.strDataSource,this.strSql);
				if(this.getBaseTag().getPage().listItemDataContainsKey(key)){
					temp = (Vector)this.getBaseTag().getPage().getListItemData(key);
					addAll(temp);
				}else{
					temp = new Vector<Item>();
					ResultSet rs = this.getUtils().executeQuery(this.strDataSource, this.strSql);
					int colCount = 0;
					if(rs != null)
						colCount = rs.getMetaData().getColumnCount();
					
					while(rs.next())
					{
						if(colCount == 1){
							String colName1 = StringHelper.getValue(rs.getMetaData().getColumnName(1));
							String colValue1 = StringHelper.getValue(rs.getString(1)) ;
							
							Item item = new Item(colValue1,
									(colName1.startsWith("i18n")) ? this.getUtils().i18n(colValue1) : colValue1);
							
							if(this.getBaseTag().isColumnEditor()){
								editorMap.put(colValue1,(colName1.startsWith("i18n")) ? this.getUtils().i18n(colValue1) : colValue1);
							}
							
							temp.add(item);
							
							if(brecordMap){
								BaseDataEntity record = new BaseDataEntity();
								record.spsv("value", colValue1);
								record.spsv("text", (colName1.startsWith("i18n")) ? this.getUtils().i18n(colValue1) : colValue1);
								recordMap.put(colValue1, record);
							}
						}else if(colCount >= 2){
							String colName2 = StringHelper.getValue(rs.getMetaData().getColumnName(2));
							String colValue2 = StringHelper.getValue(rs.getString(2)) ;
							Item item = new Item(StringHelper.getValue(rs.getString(1)),
									(colName2.startsWith("i18n")) ? this.getUtils().i18n(colValue2) : colValue2);
							
							if(this.getBaseTag().isColumnEditor()){
								editorMap.put(StringHelper.getValue(rs.getString(1)),(colName2.startsWith("i18n")) ? this.getUtils().i18n(colValue2) : colValue2);
							}
							
							BaseDataEntity record = null;
							if(brecordMap){
								record = new BaseDataEntity();
								record.spsv("value", StringHelper.getValue(rs.getString(1)));
								record.spsv("text", (colName2.startsWith("i18n")) ? this.getUtils().i18n(colValue2) : colValue2);
							}
							
							if(colCount > 2){
								for(int i = 3 ;i<=colCount ;i++){
									String colNamei = StringHelper.getValue(rs.getMetaData().getColumnName(i));
									String colValuei = StringHelper.getValue(rs.getString(i)) ;
									item.SetExtValue(StringHelper.getValue(rs.getMetaData().getColumnName(i)),
											(colNamei.startsWith("i18n")) ? this.getUtils().i18n(colValuei) : colValuei);
									if(brecordMap){
										record.spsv(StringHelper.getValue(rs.getMetaData().getColumnName(i)), (colNamei.startsWith("i18n")) ? this.getUtils().i18n(colValuei) : colValuei);
									}
								}
							}
							if(brecordMap){
								recordMap.put(StringHelper.getValue(rs.getString(1)), record);
							}
							temp.add(item);
						}
					}
					rs.close();
					
					addAll(temp);
					this.getBaseTag().getPage().addListItemData(key,temp);
					if(this.getBaseTag().isColumnEditor()){
						this.getBaseTag().getPage().addListItemData(this.getName(),editorMap);
					}
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 處理靜態数据集
	 */
	protected void processRawcodelist(){
		if(StringHelper.IsNullOrEmpty(this.strCodeList))
			return ;
		
		String [] sets = this.strCodeList.split("[;]"); 
		
		if(brecordMap){
			if(recordMap == null)
				recordMap = new HashMap<String, BaseDataEntity>();
		}
		
		if(this.getBaseTag().isColumnEditor()){
			editorMap = new HashMap();
		}
		
		for(int i = 0 ;i<sets.length;i++)
		{
			String strTemp = sets[i].trim();
			if(StringHelper.IsNullOrEmpty(strTemp))
				continue;
			
			String [] keyvalue  = strTemp.split("[|]");
			if(keyvalue.length == 2){
				if(StringHelper.IsNullOrEmpty(keyvalue[0]))
					continue;
				
				if(StringHelper.IsNullOrEmpty(keyvalue[1]))
					continue;
				
				addListItem(new Item(keyvalue[0], keyvalue[1]));
				if(this.getBaseTag().isColumnEditor()){
					editorMap.put(keyvalue[0],keyvalue[1]);
				}
				
				if(brecordMap){
					BaseDataEntity record = new BaseDataEntity();
					record.spsv("value", keyvalue[0]);
					record.spsv("text", keyvalue[1]);
					recordMap.put(keyvalue[0], record);
				}
			}else if(keyvalue.length == 1){
				if(StringHelper.IsNullOrEmpty(keyvalue[0]))
					continue;
				addListItem(new Item(keyvalue[0], keyvalue[0]));
				if(this.getBaseTag().isColumnEditor()){
					editorMap.put(keyvalue[0],keyvalue[0]);
				}
				
				if(brecordMap){
					BaseDataEntity record = new BaseDataEntity();
					record.spsv("value", keyvalue[0]);
					record.spsv("text", keyvalue[0]);
					recordMap.put(keyvalue[0], record);
				}
			}
		}
		if(this.getBaseTag().isColumnEditor()){
			this.getBaseTag().getPage().addListItemData(this.getName(),editorMap);
		}
	}
	
	/* 
	 * 加载属性值
	 */
	@Override
	public void OnSetProperty(String strName, String strValue) {
		if (strName.compareToIgnoreCase("CodeList") == 0)
		{
			this.strCodeList = strValue;
			return;
		}
		
		if (strName.compareToIgnoreCase("sql") == 0)
		{
			this.strSql = strValue;
			return;
		}
		
		if (strName.compareToIgnoreCase("dataSource") == 0)
		{
			this.strDataSource = strValue;
			return;
		}
		
		if (strName.compareToIgnoreCase("Emptysupported") == 0)
		{
			if("auto".equals(strValue)){
				this.bAutoEmpty = true;
			}
			
			this.bEmptysupported = StringHelper.GetValue(strValue, this.bEmptysupported);
			return;
		}
		
		if (strName.compareToIgnoreCase("Emptytext") == 0)
		{
			this.strEmptytext = strValue;
			return;
		}
		
		if (strName.compareToIgnoreCase("Emptyatfirst") == 0)
		{
			this.bEmptyatfirst = StringHelper.GetValue(strValue, this.bEmptyatfirst);
			return;
		}
		
		if (strName.compareToIgnoreCase("CodelistPostion") == 0)
		{
			this.strCodelistPostion = strValue;
			return;
		}
		
		
		super.OnSetProperty(strName, strValue);
	}
	
	public boolean isEmptysupported() {
		return bEmptysupported;
	}

	public void setEmptysupported(boolean bEmptysupported) {
		this.bEmptysupported = bEmptysupported;
	}
	
	public String getCodeList() {
		return strCodeList;
	}

	public void setCodeList(String strCodeList) {
		this.strCodeList = strCodeList;
	}

	public boolean isLoad() {
		return bload;
	}

	public void setLoad(boolean bload) {
		this.bload = bload;
	}

	public String getSql() {
		return strSql;
	}

	public void setSql(String strSql) {
		this.strSql = strSql;
	}

	public String getDataSource() {
		return strDataSource;
	}

	public void setDataSource(String strDataSource) {
		this.strDataSource = strDataSource;
	}
}
